from tkinter import *
from tkinter import filedialog
from up_audio1 import ssh_ctrl,SshConnectError,upload_files,write_config,read_config,SshConnectError,download_file
import threading,sys,os,shutil,datetime,tarfile,time
from queue import Queue,LifoQueue,PriorityQueue
from up_audio1 import q,event
 

LOG_LINE_NUM = 0


class App_window():

    def __init__(self,init_window_name):
        self.init_window_name=init_window_name

    def set_init_window(self):
        self.init_window_name.title("语音文件上传工具")
        self.init_window_name.geometry('1000x380+10+10')  ##设置窗口大小及初始位置

        ##标签组件

        self.result_data_label = Label(self.init_window_name, text="语音文件路径：")
        self.result_data_label.grid(row=4, column=0)
        self.log_down_data_label = Label(self.init_window_name, text="log存储路径：")
        self.log_down_data_label.grid(row=6, column=0)
        self.log_label = Label(self.init_window_name, text="提示信息：")
        self.log_label.grid(row=8, column=0)
        self.host1_data_label = Label(self.init_window_name, text="PCU1_IP：")
        self.host1_data_label.grid(row=10, column=0)
        self.host2_data_label = Label(self.init_window_name, text="PCU2_IP：")
        self.host2_data_label.grid(row=12, column=0)
        self.port_data_label = Label(self.init_window_name, text="端口PORT：")
        self.port_data_label.grid(row=14, column=0)
        self.user_data_label = Label(self.init_window_name, text="USERNAME：")
        self.user_data_label.grid(row=16, column=0)
        self.passwd_data_label = Label(self.init_window_name, text="PASSWORD：")
        self.passwd_data_label.grid(row=18, column=0)
        self.remote_data_label = Label(self.init_window_name, text="语音文件路径：")
        self.remote_data_label.grid(row=20, column=0)
        self.remote_log_data_label = Label(self.init_window_name, text="PCU_LOG路径：")
        self.remote_log_data_label.grid(row=22, column=0)


        ##文本框

        self.result_data_Text = Text(self.init_window_name, width=100, height=1)  #本地路径展示
        self.result_data_Text.grid(row=4, column=1, rowspan=2, columnspan=3)
        self.log_down_data_Text = Text(self.init_window_name, width=100, height=1)  #log存储本地路径展示
        self.log_down_data_Text.grid(row=6, column=1, rowspan=2, columnspan=3)
        self.log_data_Text = Text(self.init_window_name, width=100, height=10)  # 日志框
        self.log_data_Text.grid(row=8, column=1, columnspan=8)
        self.host1_data_Text = Text(self.init_window_name, width=100, height=1)  #HOST1
        self.host1_data_Text.grid(row=10, column=1, rowspan=2, columnspan=3)
        self.host2_data_Text = Text(self.init_window_name, width=100, height=1)  #HOST2
        self.host2_data_Text.grid(row=12, column=1, rowspan=2, columnspan=3)
        self.port_data_Text = Text(self.init_window_name, width=100, height=1)  #PORT
        self.port_data_Text.grid(row=14, column=1, rowspan=2, columnspan=3)
        self.user_data_Text = Text(self.init_window_name, width=100, height=1)  #USERNAME
        self.user_data_Text.grid(row=16, column=1, rowspan=2, columnspan=3)
        self.passwd_data_Text = Text(self.init_window_name, width=100, height=1)  #PASSWORD
        self.passwd_data_Text.grid(row=18, column=1, rowspan=2, columnspan=3)
        self.remote_data_Text = Text(self.init_window_name, width=100, height=1)  #REMOTEPASS
        self.remote_data_Text.grid(row=20, column=1, rowspan=2, columnspan=3)
        self.remote_log_data_Text = Text(self.init_window_name, width=100, height=1)  #REMOTELOG
        self.remote_log_data_Text.grid(row=22, column=1, rowspan=2, columnspan=3)


        #按钮
        self.button = Button(self.init_window_name, text="选择文件", bg="lightblue", width=10,command=self.getLocalPath)  # 调用内部方法  加()为直接调用
        self.button.grid(row=4, column=20)
        self.button = Button(self.init_window_name, text="选择路径", bg="lightblue", width=10,command=self.local_log)  # 调用内部方法 
        self.button.grid(row=6, column=20)
        self.button = Button(self.init_window_name, text="开始上传", bg="lightblue", width=10,command=self.upaudio)  # 调用内部方法 
        self.button.grid(row=8, column=20)
        self.button = Button(self.init_window_name, text="开始下载log", bg="lightblue", width=10,command=self.downlog)  # 调用内部方法 
        self.button.grid(row=8, column=30)
        self.button = Button(self.init_window_name, text="修改配置", bg="lightblue", width=10,command=self.write_conf)  
        self.button.grid(row=14, column=20)

    #获取当前时间
    def get_current_time(self):
        current_time = time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))
        return current_time

    def write_conf(self):
        host1=self.host1_data_Text.get(1.0,END).strip()
        host2=self.host2_data_Text.get(1.0,END).strip()
        port=self.port_data_Text.get(1.0,END).strip()
        username=self.user_data_Text.get(1.0,END).strip()
        password=self.passwd_data_Text.get(1.0,END).strip()
        remotepath=self.remote_data_Text.get(1.0,END).strip().replace('\\','/')
        remotelog=self.remote_log_data_Text.get(1.0,END).strip().replace('\\','/')
        # print(host1,host2,port,username,password,remotepath)
        conf_dict={'upload':{'HOST_PCU1':host1,
                                'HOST_PCU2':host2,
                                'PORT':port,
                                'USERNAME':username,
                                'PASSWORD':password,
                                'REMOTE_PATH':remotepath,
                                'LOCALE_PATH':'./',  
                                'REMOTE_LOG':remotelog  
                                }}

        # print(conf_dict)
        # conf_list=[host1,host2,port,username,password,remotepath,remotelog]
        # q.put(conf_dict,block=True,timeout=None)
        # event.set()
        # t = threading.Thread(target=self.write_log_to_Text())    
        # t.start()
        # print(conf_list)
        if(host1!='')&(host2!='')&(port!='')&(username!='')&(password!='')&(remotepath!='')&(remotelog!=''):
            write_config(conf_dict)
            n3="请认真核对新设置的配置文件，配置文件参数如下！"
            q.put((n3,conf_dict),block=True,timeout=None)
            event.set()
            t = threading.Thread(target=self.write_log_to_Text())    
            t.start()
        else:
            
            n2="配置文件参数不能为空！"
            q.put((n2,conf_dict),block=True,timeout=None)
            event.set()
            t = threading.Thread(target=self.write_log_to_Text())    
            t.start()

    def getLocalPath(self):
        foder_path=filedialog.askdirectory()   ##获取文件夹路径
        # print('文件夹路径：',foder_path)
        self.result_data_Text.delete(1.0,END)
        self.result_data_Text.insert(1.0,foder_path)   #获取到的路径输出到文本框中展示，第一个参数为行号
        return foder_path

    def upaudio(self):
        localpath=self.result_data_Text.get(1.0,END).strip().replace('\n','')
        # print(localpath)
        local_p=os.path.join(os.getcwd(),'config.ini')
        if (os.path.exists('./config.ini'))&(localpath!=''):
            try:
                conf=read_config()
                # print(conf)
                host=conf.get('upload','HOST_PCU1')
                host1=conf.get('upload','HOST_PCU2')
                username=conf.get('upload','USERNAME')
                password=conf.get('upload','PASSWORD')
                port=conf.get('upload','PORT')
                remotepath=conf.get('upload','REMOTE_PATH')
                remote_log=conf.get('upload','REMOTE_LOG')
                # local_path=conf.get('upload','lOCAL_PATH')
                # print(host,host1,username,password,remotepath)
            except IOError:
                print("Read file Somethings wrong !")
            try:
                p=threading.Thread(target=upload_files(host,username,password,remotepath,localpath))
                # p1=threading.Thread(target=upload_files(host1,username,password,remotepath,localpath))
                t = threading.Thread(target=self.write_log_to_Text())
                # t1 = threading.Thread(target=self.write_log_to_Text())
                p.start()
                # p1.start()
                t.start()
                # t1.start()
            except (SshConnectError,IOError):
                print("PCU1 upload Somethings wrong !")
                n1=host+"  PCU1 文件上传失败，请检查设备连接状态！"
                q.put(n1,block=True,timeout=None)
                event.set()
                t = threading.Thread(target=self.write_log_to_Text())
                t.start()
            try:
                p=threading.Thread(target=upload_files(host1,username,password,remotepath,localpath))
                t = threading.Thread(target=self.write_log_to_Text())
                p.start()
                t.start()

            except (SshConnectError,IOError):
                print("PCU2 upload Somethings wrong !")
                n1=host1+"  PCU2 文件上传失败，请检查设备连接状态！"
                q.put(n1,block=True,timeout=None)
                event.set()
                t = threading.Thread(target=self.write_log_to_Text())    
                t.start()
            
        elif(os.path.exists(local_p)):
            n1="请选择语音文件所在文件夹，然后点击开始上传按钮。"
            q.put(n1,block=True,timeout=None)
            event.set()
            t = threading.Thread(target=self.write_log_to_Text())    
            t.start()
        else:
            n1="配置文件不存在\n1、请重新设置配置文件，将PCU1_IP、PCU2_IP、端口PORT、USERNAME、PASSWORD、语音文件路径、PCU_LOG路径参数填写，点击右侧修改配置按钮。"
            q.put(n1,block=True,timeout=None)
            event.set()
            t = threading.Thread(target=self.write_log_to_Text())    
            t.start()

    def local_log(self):
        log_local_path=filedialog.askdirectory()   ##获取文件夹路径
        # print('文件夹路径：',log_local_path)
        self.log_down_data_Text.delete(1.0,END)
        self.log_down_data_Text.insert(1.0,log_local_path)   #获取到的路径输出到文本框中展示，第一个参数为行号
        return log_local_path

    def downlog(self):
        log_local_path=self.log_down_data_Text.get(1.0,END).strip().replace('\n','')
        # print(log_local_path)
        local_p=os.path.join(os.getcwd(),'config.ini')
        if (os.path.exists('./config.ini'))&(log_local_path!=''):
            try:
                conf=read_config()
                # print(conf)
                host=conf.get('upload','HOST_PCU1')
                host1=conf.get('upload','HOST_PCU2')
                username=conf.get('upload','USERNAME')
                password=conf.get('upload','PASSWORD')
                port=conf.get('upload','PORT')
                remotepath=conf.get('upload','REMOTE_PATH')
                remote_log=conf.get('upload','REMOTE_LOG')
                # print(host,host1,username,password,remotepath)
            except IOError:
                print("Read file Somethings wrong !")
            try:
                remote_log=remote_log+'/log.tar'
                # print(remote_log,log_local_path)
                log_local=log_local_path+'/PCU1_log'
                if os.path.exists(log_local):
                    shutil.rmtree(log_local)
                os.mkdir(log_local)
                p=threading.Thread(target=download_file(host,username,password,remote_log,log_local))
                t = threading.Thread(target=self.write_log_to_Text())
                p.start()
                t.start()
            except SshConnectError:
                print("PCU1 download Somethings wrong !")
                n1=host+"  PCU1 log文件下载失败，请检查设备连接状态！"
                q.put(n1,block=True,timeout=None)
                event.set()
                t = threading.Thread(target=self.write_log_to_Text())    
                t.start()
            try:
                # remote_log=remote_log+'/log.tar'
                # print(remote_log,log_local_path)
                log_local=log_local_path+'/PCU2_log'
                if os.path.exists(log_local):
                    shutil.rmtree(log_local)
                os.mkdir(log_local)
                p1=threading.Thread(target=download_file(host1,username,password,remote_log,log_local))
                t1 = threading.Thread(target=self.write_log_to_Text())
                p1.start()
                t1.start()
            except SshConnectError:
                print("PCU2 download Somethings wrong !")
                n9=host1+"  PCU2 log文件下载失败，请检查设备连接状态！"
                q.put(n9,block=True,timeout=None)
                event.set()
                t1 = threading.Thread(target=self.write_log_to_Text())    
                t1.start()
        elif(os.path.exists(local_p)):
            n1="请选择存储log文件夹，然后点击开始下载log按钮。"
            q.put(n1,block=True,timeout=None)
            event.set()
            t = threading.Thread(target=self.write_log_to_Text())    
            t.start()
        else:
            n1="配置文件不存在\n1、请重新设置配置文件，将PCU1_IP、PCU2_IP、端口PORT、USERNAME、PASSWORD、语音文件路径、PCU_LOG路径参数填写，点击右侧修改配置按钮。"
            q.put(n1,block=True,timeout=None)
            event.set()
            t = threading.Thread(target=self.write_log_to_Text())    
            t.start()

    def write_log_to_Text(self):
        global LOG_LINE_NUM
        # current_time = self.get_current_time()
        while True:
            if q.empty() is False:
                logmsg=q.get(block=True,timeout=None)
                # print(logmsg)     
                # q.task_done() 
                event.clear()  
                logmsg_in = str(logmsg) + "\n"      #换行
                time.sleep(0.0001)
                self.log_data_Text.insert(END, logmsg_in)
                self.log_data_Text.see(END)
                self.log_data_Text.update()

                # if LOG_LINE_NUM <= 140:
                #     time.sleep(0.2)
                #     self.log_data_Text.insert(END, logmsg_in)
                #     LOG_LINE_NUM = LOG_LINE_NUM + 1
                # else:
                #     # self.log_data_Text.delete(1.0,2.0)
                #     time.sleep(0.2)
                #     self.log_data_Text.insert(END, logmsg_in)
                #     self.log_data_Text.see(END)
                #     self.log_data_Text.update()
            else:
                break


def gui_start():
    init_window=Tk()              #实例化出一个父窗口
    ZMJ_PORTAL = App_window(init_window)
    # 设置根窗口默认属性
    ZMJ_PORTAL.set_init_window()

    init_window.mainloop() 

gui_start()
